<?php
/**
 * Created by PhpStorm.
 * User: brain
 * Date: 2016/3/25
 * Time: 18:05
 */

namespace App\Common;


use App\Utils\ProjectDicts;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use p5\objects\CollectionUtils;

class TableCacher
{
    static protected $table = "menu";


    static public function findIntoList($propertyName, $propertyValue)
    {
        $list = self::all();
        return CollectionUtils::findAll($list, [$propertyName => $propertyValue]);
    }

    static public function findOne($propertyName, $propertyValue)
    {
        $list = self::findIntoList($propertyName, $propertyValue);
        if (empty($list)) {
            return [];
        }
        return $list[0];
    }

    static public function all()
    {
        $key = self::getCacheKey();
        // echo $key ;
        return Cache::get($key, function () use ($key) {
            $sql = self::getLoadSql();
            if (empty($sql)) {
                $sql = "SELECT * FROM " . self::$table;
            }
            $list = DB::select($sql);
            if (empty($list)) {
                Cache::forever($key, []);
                return [];
            }
            $matrix = json_decode(json_encode($list), true);
            Cache::forever($key, $matrix);
            return $matrix;
        });
    }

    static public function addRecord($record)
    {
        if (is_object($record)) {
            $record = json_decode(json_encode($record), true);
        }
        $all = self::all();
        array_push($all, $record);
        $key = self::getCacheKey();
        Cache::forever($key, $all);
    }

    static public function getLoadSql()
    {
        return "";
    }

    static public function clearCache()
    {
        Cache::forget(self::getCacheKey());
    }

    static public function refresh()
    {
        self::clearCache();
        self::all();
    }

    static public function getCacheKey()
    {
        return ProjectDicts::PROJECT_UNIQUE_ID . ":" . get_called_class() . ":cache.datas";
    }
}